package com.kun.service.handle;

import com.kun.utils.AjaxResult;
import com.kun.exception.ServiceException;
import com.kun.utils.JsonUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        if (authException instanceof InsufficientAuthenticationException) {
            sendRespose(response, HttpStatus.UNAUTHORIZED, "访问此资源需要完全身份验证");
            return;
        }
        Throwable cause = authException.getCause();
        if (cause instanceof ServiceException serviceException) {
            sendRespose(response, serviceException.getHttpStatus(), serviceException.getMessage());
            return;
        }
        sendRespose(response, HttpStatus.BAD_REQUEST, authException.getMessage());
    }

    private static void sendRespose(HttpServletResponse response, HttpStatus httpStatus, String message) throws IOException {
        response.setStatus(httpStatus.value());
        response.setContentType("application/json;charset=UTF-8");
        ResponseEntity<AjaxResult> response1 = AjaxResult.error(httpStatus, message);
        response.getWriter().write(JsonUtils.toJson(response1.getBody()));
    }
}
